package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"repo-mng-sys/models"
	"repo-mng-sys/redis"
	"strconv"
	"time"
)

func RepoList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size

	var repo []*models.Repo

	redis_key := "repo_list_" + strconv.Itoa(page)
	cacheData, _ := redis.Rdb.Get(redis.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Offset(offset).Limit(size).Order("id desc").Find(&repo)
		jsonData, _ := json.Marshal(repo)
		redis.Rdb.Set(redis.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &repo)
	}

	var total int64
	models.DB.Model(&models.Repo{}).Count(&total)

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "success",
		"data":  repo,
		"total": total,
	})
	return
}

func RepoShow(c *gin.Context) {
	id := c.Query("id")

	var repo *models.Repo
	models.DB.Where("id=?", id).Find(&repo)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": repo,
	})
}
